#include "sqltablemodel.h"

#include <QHash>
#include <QtSql/QSqlDatabase>
#include <QtSql/QSqlField>
#include <QtSql/QSqlRecord>
#include <QtSql/QSqlQuery>


SqlTableModel::SqlTableModel(QObject *parent, QSqlDatabase db)
    : QSqlRelationalTableModel(parent, db),
      m_readOnly(false)
{
}

SqlTableModel::~SqlTableModel()
{
}

void SqlTableModel:: setTable(const QString &table)
{
    QSqlRelationalTableModel::setTable(table);
    QSqlQuery query("PRAGMA table_info("+table+")");
    if( query.exec() ) {
        m_fieldsType.clear();
        while(query.next()) {
            QString name = query.record().value("name").toString();
            QString typeString = query.record().value("type").toString();
            QVariant::Type type;
            if(typeString.compare("date", Qt::CaseInsensitive) == 0)
                type = QVariant::Date;
            else if( typeString.compare("integer", Qt::CaseInsensitive) == 0 || typeString.compare("int", Qt::CaseInsensitive) )
                type = QVariant::Int;
            else
                type = QVariant::String;
            m_fieldsType[name] = type;
        }
    }
}

QVariant SqlTableModel::data(const QModelIndex &item, int role) const
{
    QVariant result = QSqlRelationalTableModel::data(item, role);
    if( role == Qt::DisplayRole ) {
        QSqlRecord rec = record();
        QString fieldName = rec.fieldName(item.column());
        if( m_fieldsType[fieldName] == QVariant::Date ) {
            QString s = result.toString();
            s.insert(4,'.');
            s.insert(7,'.');
            result = s;
        }
    }
    return result;
}

Qt::ItemFlags SqlTableModel::flags(const QModelIndex &index) const
{
    Qt::ItemFlags flags = QSqlRelationalTableModel::flags(index);
    if ( m_readOnly )
        flags ^= Qt::ItemIsEditable;
    return flags;
}
